import re

from loguru import logger

from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.muilty_coroutine_util import concurrency


class HandPheasantCollegeProcessor(BaseProcessor):
    def __init__(self):
        pass

    async def parse_and_save_data(self, result_json):
        result_data = result_json['data']
        tasks = []
        for item in result_data['informal']:
            college_name = item['name']
            province = item['province']
            tasks.append({
                "province_name": province,
                "university_name": college_name
            })
        await self.__save(tasks=tasks)


    @concurrency(5)
    async def __save(self, **params):
        task = params['task']
        mapping = db.MysqlMapping("tb_university_pheasant")
        if await self.check_exist(mapping, task):
            logger.info("数据已存在!")
        else:
            await mapping.insert(task)

    async def check_exist(self, mapping, data):
        condition = {
            "university_name": data['university_name']
        }
        result = await mapping.query(condition, ["id"])
        if result:
            return result[0][0]